// Code scaffolded by goctl. Safe to edit.
// goctl 1.9.1

package file

import (
	"context"
	"encoding/json"
	"fmt"
	"mime/multipart"
	"strconv"

	"audio-server/internal/svc"
	"audio-server/internal/types"

	"github.com/volcengine/ve-tos-golang-sdk/v2/tos"
	"github.com/zeromicro/go-zero/core/logx"
)

type FileOssUploadLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewFileOssUploadLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FileOssUploadLogic {
	return &FileOssUploadLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *FileOssUploadLogic) FileOssUpload(file multipart.File, header *multipart.FileHeader) (resp *types.FileOssRes, err error) {
	userId, _ := l.ctx.Value("userId").(json.Number).Int64()
	uploadDir := "uploads/"
	filename := header.Filename
	fileSize := header.Size
	filePath := uploadDir + strconv.FormatInt(userId, 10) + "/" + filename

	client := l.svcCtx.TOSClient
	_, err = client.PutObjectV2(l.ctx, &tos.PutObjectV2Input{
		PutObjectBasicInput: tos.PutObjectBasicInput{
			Bucket: l.svcCtx.Config.TosConfig.Bucket,
			Key:    filePath,
		},
		Content: file,
	})
	if err != nil {
		return nil, err
	}
	url := "https://audio-server.tos-cn-guangzhou.volces.com/"

	res := fmt.Sprintf("%s%s", url, filePath)

	return &types.FileOssRes{
		Name: filename,
		Src:  res,
		Size: fileSize,
	}, nil
}
